package com.zcf.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zcf.common.json.Body;
import com.zcf.common.utils.MD5Util;
import com.zcf.mapper.ConsoleuserMapper;
import com.zcf.mapper.LoginLogMapper;
import com.zcf.pojo.Consoleuser;
import com.zcf.pojo.LoginLog;
import com.zcf.vo.out.LayuiJson;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZhaoQi
 * @since 2019-03-18
 */
@Service("ConsoleuserServiceImpl")
public class ConsoleuserServiceImpl  {
	@Autowired
	ConsoleuserMapper cm;
	@Autowired
	LoginLogMapper lm;
	/**
	 * 后台登录
	 * @param cl
	 * @return
	 */

	public Body login(Consoleuser cl, HttpServletRequest request) {
		if(cl.getPassword() != null){
			cl.setPassword(MD5Util.MD5EncodeUtf8(cl.getPassword()));
		}
		String ip = UserServiceImpl.getIpAddress(request);
		LoginLog log = new LoginLog();
		log.setCreateTime(new Date());
		log.setIp(ip);
		log.setUserName(cl.getUsername());
		/*try {
			log.setAddress(UserServiceImpl.getAddresses("ip="+ip, "utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}*/
		log.insert();

		Consoleuser consoleuser = cm.selectOne(cl);
		if (consoleuser == null) {
			return Body.BODY_451;
		}
		return Body.newInstance(consoleuser);
	}

	/**
	 * 管理员修改账号或 密码
	 * @param cl
	 * @return
	 */
	public Body update(Consoleuser cl) {
		if(cl.getPassword() != null){
			cl.setPassword(MD5Util.MD5EncodeUtf8(cl.getPassword()));
			cl.setId((long) 1);
			boolean b = cl.updateById();
			if(b){
				return Body.BODY_200;
			}
			return Body.BODY_451;
		}


		return null;
	}
	/**
	 * 获取登录日志
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public LayuiJson getlogin(int pageNum, int pageSize) {
		LayuiJson lj = new LayuiJson();
		Wrapper w = new EntityWrapper();
		List list = lm.selectPage(new Page<>(pageNum, pageSize), w);
		Integer count = lm.selectCount(w);
		if (list != null) {
			lj.setCode(0);
			lj.setCount(count);
			lj.setData(list);
			lj.setMsg("成功");
			return lj;
		}
		lj.setCode(1);
		lj.setCount(count);
		lj.setData(null);
		lj.setMsg("暂无数据");
		return lj;
	}

}
